<?php

class CommonAction extends Action {

    function _initialize() {
       
    	import('@.ORG.Util.Cookie');
        // 用户权限检查
        if (C('USER_AUTH_ON') && !in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
        	//检查子类模块有没有方法无须验证qing1000 2012-6-12>>
        	//配置中无须验证的方法，是对于所有模块者是这样，不管模块是不否要验证
        	if(isset($_SESSION['administrator']))return;//是管理员直接返回
        	if(isset($_SESSION['_ACCESS_LIST'])){
				if(isset($_SESSION['_ACCESS_LIST'][strtoupper(APP_NAME)][strtoupper(MODULE_NAME)])){
					if (method_exists($this, '_noAuth')) {//子类无须验证的方法
						if($this->_noAuth())return;
					}
				}
			}
			//qing1000 2012-6-12>>
        	import('@.ORG.Util.RBAC');
            if (!RBAC::AccessDecision()) {
                //检查认证识别号
                if (!$_SESSION [C('USER_AUTH_KEY')]) {
                    //跳转到认证网关
                    redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
                }
                // 没有权限 抛出错误
                if (C('RBAC_ERROR_PAGE')) {
                    // 定义权限错误页面
                 //   redirect(C('RBAC_ERROR_PAGE'));
                 	$this->error('此操作没有权限!');
                } else {
                    if (C('GUEST_AUTH_ON')) {
                        $this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY'));
                    }
                    // 提示错误信息
                  $this->error('你在访问模块：'.MODULE_NAME.'>>'.ACTION_NAME.'>>操作上'.L('_VALID_ACCESS_'));
                 // $this->assign('mess','你在访问模块：'.MODULE_NAME.'>>'.ACTION_NAME.'>>操作上'.L('_VALID_ACCESS_'));
                  //$this->display('Public:nopower');
                  // Log::write('你在访问模块：'.MODULE_NAME.'>>'.ACTION_NAME.'>>操作上'.L('_VALID_ACCESS_'));
                  // exit ;
                }
            }
        }
    }

    // 工具栏按钮页面
    protected  function _getButton() {
    
    	if(isset($_SESSION[C('USER_AUTH_KEY')])) {
    		$button  = array();
    		if(isset($_SESSION['button_'.MODULE_NAME.'_'.$_SESSION[C('USER_AUTH_KEY')]])) {
    
    			//如果已经缓存，直接读取缓存
    			$button   =   $_SESSION['button_'.MODULE_NAME.'_'.$_SESSION[C('USER_AUTH_KEY')]];
    		}else {
    			$node    =   M("Node");
    			$where['level']=3;
    			$where['status']=1;
    			$where['is_show']=1;
    			$where['pid']=$node->getFieldByName(MODULE_NAME,'id');
    			$list	=	$node->where($where)->field('id,name,group_id,title,nodeicon')->order('sort asc')->select();
    			if(!$list)return ;
    			if (isset($_SESSION['_ACCESS_LIST']))$accessList = $_SESSION['_ACCESS_LIST'];
    			foreach($list as $key=>$module) {
    				if(isset($accessList[strtoupper(APP_NAME)][strtoupper(MODULE_NAME)][strtoupper($module['name'])]) || $_SESSION['administrator']) {
    					//设置模块访问权限
    					$module['access'] =   1;
    					$button[$key]  = $module;
    				}
    			}
    		//	$_SESSION['button'.$_SESSION[C('USER_AUTH_KEY')]]	=	$button;
    		}
    		$this->assign('button',$button);
    	}
    	
    }
    
    
    function getReturnUrl() {
        return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION');
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param string $name 数据对象名称
      +----------------------------------------------------------
     * @return HashMap
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _search($name = '') {
        //生成查询条件
        if (empty($name)) {
            $name = $this->getActionName();
        }
        $name = $this->getActionName();
        $model = D($name);
        $map = array();
        foreach ($model->getDbFields() as $key => $val) {
            if (isset($_REQUEST [$val]) && $_REQUEST [$val] != '') {
                $map [$val] = $_REQUEST [$val];
            }
        }
        return $map;
    }

 
    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false) {
        //排序字段 默认为主键名
        if (isset($_REQUEST ['_order'])) {
            $order = $_REQUEST ['_order'];
        } else {
            $order = !empty($sortBy) ? $sortBy : $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset($_REQUEST ['_sort'])) {
            $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count('id');
        if ($count > 0) {
            import("@.ORG.Util.Page");
            //创建分页对象
            if (!empty($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = '';
            }
            $p = new Page($count, $listRows);
            //分页查询数据

            $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            if(count($map)){//检查是否过滤条件qing100
            	foreach ($map as $key => $val) {
            		if (!is_array($val)) {
            			$p->parameter .= "$key=" . urlencode($val) . "&";
            		}
            	}	
            }
            
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            //模板赋值显示
            $this->assign('list', $voList);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }
        Cookie::set('_currentUrl_', __SELF__);
        return $voList;
    }
   
    /*  新增(add)与写入(insert)的权限,合并,编辑(edit)与更新(update)的权限俣并
     *  通过判断请求类型处理,显示新增页面还是保存到数据库;
     *  get请求是打开一个页面,post是保存数据
     *  在子类中,如用到前置或后置,也要作相应的处理.
     */
            
    public function add() {
    	if (!$this->isPost()){  //get请求,显示编辑页面
    	 	$this->display();
    	}
    	else{//保存到数据库
    		$name = $this->getActionName();
    		$model = D($name);
    		if (false === $model->create()) {
    			$this->error($model->getError());
    		}
    		//保存当前数据对象
    	//	Log::write(json_encode($_POST));
    		$list = $model->add();
    		if ($list !== false) { //保存成功
    			$this->assign('jumpUrl', Cookie::get('_currentUrl_'));
    			$this->success('新增成功!');
    		} else {
    			//失败提示
    			$this->error('新增失败!');
    		}	
    	}
    }
  
     //修改方法
    public function edit() {
    	$name = $this->getActionName();
    	$model = D($name);
    	if (!$this->isPost()){  //get请求,显示编辑页面
	       	$id = $_REQUEST [$model->getPk()];
        	$vo = $model->getById($id);
        	$this->assign('vo', $vo);
        	$this->assign('id', $id);
        	$this->display();
    	}
    	else{//保存到数据库
    		if (false === $model->create()) {
    			$this->error($model->getError());
    		}
    		$list = $model->save();
    		if (false !== $list) {
    			$this->success('编辑成功!');
    		
    		} else {
    			$this->error('编辑失败!');
    		}
    		 
    	}
    }
    //查看数据
    public function view() {
    	$this->edit();
    }
    //直接删除数据
    public function del() {
    	//删除指定记录
    	$name = $this->getActionName();
    	$model = D($name);
    	if (!empty($model)) {
    		$pk = $model->getPk();
    		$id = $_REQUEST [$pk];
    		if (isset($id)) {
    			$condition = array($pk => array('in', explode(',', $id)));
    			if (false !== $model->where($condition)->delete()) {
    				$this->success('删除成功！');
    			} else {
    				$this->error('删除失败！');
    			}
    		} else {
    			$this->error('非法操作');
    		}
    	}
    }
    
    //新增数据库
    function insert() {
    	//B('FilterString');
    	$name = $this->getActionName();
    	$model = D($name);
    	if (false === $model->create()) {
    		$this->error($model->getError());
    	}
    	//保存当前数据对象
    	$list = $model->add();
    	if ($list !== false) { //保存成功
    		$this->assign('jumpUrl', Cookie::get('_currentUrl_'));
    		$this->success('新增成功!');
    	} else {
    		//失败提示
    		$this->error('新增失败!');
    	}
    }
    //修改数据库
    function update() {
        //B('FilterString');
    	
    	$name = $this->getActionName();
        $model = D($name);
        $data=$_POST;
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        
     
        $list = $model->save();
        if (false !== $list) {
            //成功提示
          //  $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
            $this->success('编辑成功!');
            
        } else {
            //错误提示
            $this->error('编辑失败!');
        }
       
    }

    /**
      +----------------------------------------------------------
     * 默认删除操作
          +----------------------------------------------------------
     */
    public function delete() {
        //删除指定记录
        $name = $this->getActionName();
        $model = M($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                $list = $model->where($condition)->setField('status', - 1);
                if ($list !== false) {
                    $this->success('删除到回收站成功！');
                } else {
                    $this->error('删除回收站失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
    }
    

    public function clear() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            if (false !== $model->where('status=1')->delete()) {
                $this->assign("jumpUrl", $this->getReturnUrl());
                $this->success(L('_DELETE_SUCCESS_'));
            } else {
                $this->error(L('_DELETE_FAIL_'));
            }
        }
        $this->forward();
    }

    

    public function checkPass() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->checkPass($condition)) {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态批准成功！');
        } else {
            $this->error('状态批准失败！');
        }
    }

    public function recycle() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->recycle($condition)) {

            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态还原成功！');
        } else {
            $this->error('状态还原失败！');
        }
    }

    public function recycleBin() {
        $map = $this->_search();
        $map ['status'] = - 1;
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
    }
    /**
     +----------------------------------------------------------
     * 默认禁用操作
     *
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    public function forbid() {
    	$name = $this->getActionName();
    	$model = D($name);
    	$pk = $model->getPk();
    	$id = $_REQUEST [$pk];
    	$condition = array($pk => array('in', $id));
    	$list = $model->forbid($condition);
    	if ($list !== false) {
    		//$this->assign("jumpUrl", $this->getReturnUrl());
    		$this->success('状态禁用成功');
    	} else {
    		$this->error('状态禁用失败！');
    	}
    }
    /**
      +----------------------------------------------------------
     * 默认恢复操作
     *
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws FcsException
      +----------------------------------------------------------
     */
    function resume() {
        //恢复指定记录
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_POST [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->resume($condition)) {
           // $this->assign("jumpUrl", $this->getReturnUrl());
        	$this->success("状态恢复成功！");
        } else {
            $this->error('状态恢复失败！');
          
        }
    }

    function saveSort() {
        $seqNoList = $_POST ['seqNoList'];
        if (!empty($seqNoList)) {
            //更新数据对象
            $name = $this->getActionName();
            $model = D($name);
            $col = explode(',', $seqNoList);
            //启动事务
            $model->startTrans();
            foreach ($col as $val) {
                $val = explode(':', $val);
                $model->id = $val [0];
                $model->sort = $val [1];
                $result = $model->save();
                if (!$result) {
                    break;
                }
            }
            //提交事务
            $model->commit();
            if ($result !== false) {
                //采用普通方式跳转刷新页面'排序数据更新成功'
                $this->success('排序数据更新成功');
            } else {
                $this->error($model->getError());
            }
        }
    }

    protected function _searchRule($name = '') {
    	//用于ligerui查询过滤规划，{'op':'and','rules':[{'op':'like','feild':'account','value':'qing','type':'string'},{}]'}
    	//public function test() {
    //	foreach($_REQUEST as $index => $value) echo "\$_REQUEST[$index] = $value", "<BR>";
    	// $this->display();
    	//  $this->success('hhh');
    	if (isset($_REQUEST ['where'])){
    		$where =json_decode($_REQUEST ['where'],true);
    		$op=$where['op'];
    		$rules=$where['rules'];
    		$map1=array();
    		if(isset($rules)){
    			foreach($rules as $index => $ruleField){
    				$map1[$ruleField['field']]=array($ruleField['op'],$ruleField[value]);
    			}
    		}
    		return $map1;
    	}

    }
    
    protected function _searchList($model, $map, $sortBy = '', $asc = true) {
    	//排序字段 默认为主键名
    	if (isset($_REQUEST ['_order'])) {
    		$order = $_REQUEST ['_order'];
    	} else {
    		$order = !empty($sortBy) ? $sortBy : $model->getPk();
    	}
    	//排序方式默认按照倒序排列
    	//接受 sost参数 0 表示倒序 非0都 表示正序
    	if (isset($_REQUEST ['_sort'])) {
    		$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
    	} else {
    		$sort = $asc ? 'asc' : 'desc';
    	}
    	//取得满足条件的记录数
    	$count = $model->where($map)->count('id');
    	if ($count > 0) {
    		 
    		//创建分页对象
    		if (!empty($_REQUEST ['page'])) {
    			$page = $_REQUEST ['page'];
    		} else {
    			$page = '';
    		}
    		if (!empty($_REQUEST ['pagesize'])) {
    			$pagesize = $_REQUEST ['pagesize'];
    		} else {
    			$pagesize = '';
    		}
    
    
    		//$voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
    		$voList = $model->where($map)->order("`" . $order . "` " . $sort)->Page($page.','.$pagesize)->select();
    		//Log::write($model->getlastsql());
    	}
    	Cookie::set('_currentUrl_', __SELF__);
    	//return $voList;
    	return array('Rows'=>$voList,'Total'=>$count);
    }
    
    //返回的列表,格式为josn;代替_index
    public function getlist() {
    	//列表过滤器，生成查询Map对象
    	$map = $this->_searchRule();
    	if (method_exists($this, '_filter')) {
    		$this->_filter($map);
    	}
    	$name = $this->getActionName();
    	$model = D($name);
    	if (!empty($model)) {
    		$result=$this->_searchList($model, $map);
    	//	$result=array('Rows'=>$rows,'Total'=>count($rows));
    		echo json_encode($result);
    	}
    	
    
    }
    //打开编辑窗口,模板addOrUpdate.html,参数id;
    public function addOrUpdate() {
    	$name = $this->getActionName();
    	$model = M($name);
    	$id = $_REQUEST [$model->getPk()];
    	if($id==""){
    		$id=0;
    	}
    	$this->assign('id', $id);
    	$this->display();
    }
        
    function getById() {
    	$name = $this->getActionName();
    	$model = D($name);
    	$id = $_REQUEST [$model->getPk()];
    	echo json_encode($model->getById($id));
    }
    

}

?>